<?php

	/** Une classe pour representer les villes dans le système
	 * auteur : Sebastian Mosser
	 */
	 
	 
	 class City implements iPersistantData, iHTMLViewable {
	 
	 
	 	public static $ForeignCity = "FOREIGN";
	 	public static $ForeignDisplay = "N/A";
	 	
	 	
	 	private $_id;
	 	private $_zip;
	 	private $_name;
	 
	 
	 	public function __construct($zip, $name, $id = -1) {
	 		$this->_id = $id;
	 		$this->_zip = $zip;
	 		$this->_name = $name;
	 	}
	 	
	 	public function getZip() { return $this->_zip; }
	 	
	 	/** Implémentation de l'interface de données persistantes **/
	 	public static function createTable() {
	 	 	$myDb = Database::getSingleton();
	 	 	
	 	 	$query  = "CREATE TABLE IF NOT EXISTS `city`(\n";
	 	 	$query .= "  `id`   INTEGER NOT NULL PRIMARY KEY auto_increment,\n";
	 	 	$query .= "  `zip`  VARCHAR(10) NOT NULL,\n";
	 	 	$query .= "  `name` VARCHAR(30) NOT NULL);\n";
	 	 	
	 	 	$myDb->execute($query);
	 	 	
	 	}
	 	 
	 	public static function dropTable() {
	 	 	$query = "DROP TABLE IF EXISTS `city`";
	 	 	$myDb = Database::getSingleton();
	 	 	$myDb->execute($query);
	 	}
	 	 
	 	public function create() {
	 	 	if ($this->_id != -1)
	 	 		throw new RuntimeException("City/create()","This object is still present in database !!");
	 	 	
	 	 	$myDb = Database::getSingleton();
	 	 	
	 	 	$zip  = Database::escape($this->_zip);
	 	 	$name = Database::escape($this->_name);
	 	 	
	 	 	$query  = "INSERT INTO `city` VALUES (\n";
	 	 	$query .= " '','$zip','$name');";
	 	 	
	 	 	/**
	 	 	$myDb->execute($query);
	 	 	
	 	 	($myDb->lastKeyValue() != 0 ?
	 	 		$this->_id = $myDb->lastKeyValue() :
	 	 		$this->_id = -1);
	 	 	**/
	 	  $result = $myDb->executeInsert($query);
		  if ($result[0] != 0)
			  $this->_id = $result[0];
		  else
			  $this->id = -1;
	 	}
		
		public static function read($key) {
			$myDb = Database::getSingleton();
			$key = Database::escape($key);
			$query = "SELECT * FROM `city` WHERE `id` = $key;";
			$ans = Database::assoc($myDb->execute($query));
			if (! $ans) {
				throw new Exception("City/read() : Unknown key $key !",0);
			}
			
			$aCity = new City($ans["zip"],$ans["name"],$ans["id"]);
			
			return $aCity;
		
		}
	 	
	 	public function update() {
	 		$myDb = Database::getSingleton();
	 		if ($this->_id == -1)
	 			throw new RuntimeException("City/update()","This object isn't present in database !!");
	 		
	 		$query  = "UPDATE `city` SET \n";
	 		$query .= " `zip` = '$this->_zip', \n";
	 		$query .= " `name` = '$this->_name' \n";
	 		$query .= "  WHERE `id` = $this->_id; ";
	 		
	 		$myDb->executeQuery($query);
	 	
	 	}
	 	
	 	public function delete() {
	 		$myDb = Database::getSingleton();
	 		
	 		if ($this->_id == -1)
	 			throw new RuntimeException("City/delete()","This object isn't present in database !!");
	 		$query = "DELETE FROM `city` WHERE `id` = $this->_id;"; 
	 	
	 	}
	 	
	 	public function tag() {
	 		$tmp = array();
	 		$tmp[0] = "City";
	 		$tmp[1] = $this->_id;
	 		return $tmp;
	 	}
	 	
	 	public function soundsLike($o) {
	 		return ($this->_zip == $o->_zip && $this->_name == $o->_name);
	 	}
	 	
	  /** Fin de l'implémentation des données persistantes **/
	 
	  // Compte le nombre de villes présentes dans le système
	  public static function howMany() {
	 		$query = "SELECT COUNT(*) AS result FROM `city`;";
	 		$myDb =  Database::getSingleton();
	 		$ans = Database::assoc($myDb->execute($query));
	 		return $ans["result"];
	  }
	 
	 
	  /** Implémentation de l'interface de vision HTML **/
	
	  public function displayLong() {
	  	$zip = self::displayZip($this->_zip); 
	 		$ans = "<ul>\n";
	 		$ans .= "  <li> Identifiant Balloon : ". $this->_id   ."</li>\n";
	 		$ans .= "  <li> Code Postal : "        . $zip         ."</li>\n";
	 		$ans .= "  <li> Nom de la vile : "     . $this->_name ." </li>\n";
	 		$ans .= "</ul>\n";
	 		return $ans;
	  }
	
	  public function displayShort() {
	  	$zip = self::displayZip($this->_zip); 
	  	$ans = "[ ". $zip ." ] " . $this->_name;
	  	return $ans;
	  }
	
	  public function displayInline($scriptUrl="") {
	  	$ans = "";
	   $zip = self::displayZip($this->_zip); 
	  	if ($scriptUrl == "") {
	  		$ans .= "<td><code>" . $zip . " </code></td> ";
	  		$ans .= "<td> " . $this->_name ." </td>";
	  	}
	  	else {
	  		$ans .= "<td> <code> <a href=\"".$scriptUrl."\" > ";
	  		$ans .= $this->_zip ." </a></code></td>";
	  		$ans .= "<td> " . $this->_name . "</td>";
	  	}
	  	return $ans . "\n";
	  }
	 
	  /** Fin de l'intervalle de vision HTML **/
	  
	  /** Implementation de l'interface de recherche **/
	  
		public static function lookFor($filter) {
			if (! is_array($filter))
				throw new RuntimeException("City/lookFor","bad parameter !!");

			$zip = Database::escape(PropRetriever::getProp($filter,"zip"));
			$name = Database::escape(PropRetriever::getProp($filter,"name"));
			
			if ($zip == "" && $name == "")
				return False;
			
			$query = "SELECT * FROM `city` WHERE ";
			
			if ($zip != "" && $name != "") {
				$query .= "  `zip`  LIKE \"" . $zip  . "%\" AND ";
				$query .= "  `name` LIKE \"" . $name . "%\" ; ";
			}
			else if ($zip != "") {
				$query .= "  `zip`  LIKE \"" . $zip  . "%\" ; ";
			}
			else {
				$query .= "  `name` LIKE \"" . $name . "%\" ; ";
			}
		
			$myDb = Database::getSingleton();
			return $myDb->execute($query);
		
		
		}
	
		public static function showResult($resultSet, $scriptUrl = "") {
			
			$result  = "<div align=\"center\">\n";
			
			if (! $resultSet)
				return "Veuillez affiner votre demande, il y a trop de réponses ...";
			
			$bad = "<center> La recherche n'a donné <span class=\"error\">aucun</span> résultats ... </center></div>";
			
      $good = "  <table class=\"resultset\">\n";
      $good .= "    <tr><th>Code Postal</th><th>Ville</th></tr>\n";
			$i = 0;
			while (($row = Database::assoc($resultSet)) != False) {
	      	$i++;
	      	$good .= "    <tr>";
	      	$good .= City::read($row["id"])->displayInline($scriptUrl);
	      	$good .= "</tr>\n";
	   }
	   
	   $good .= "  </table>\n</div>";

		 if ($i == 0)
		 	 return $result.$bad;
		 else
	   	 return $result.$good;
		
		}
	  
	  /** Fin de l'implementation de l'interface de recherche **/
	  
	  	  
	  public static function getAsList($zip, $selected = False) {
	  	$sql = "SELECT * FROM `city` WHERE `zip` = '$zip';";
	  	$myDb = Database::getSingleton();
	  	$ans = $myDb->execute($sql);
	  	
	  	if (! $ans)
	  		return -1;
	  	$result = "";
	  	while(($row = Database::assoc($ans)) != False) {
	  		if ($row["id"] == $selected) {
	  			$result .= "<option value=\"".$row["id"]."\" selected>";
	  			$result .= $row["name"]." </option> \n";
	  		}
	  		else {
	  			$result .= "<option value=\"".$row["id"]."\" >";
	  			$result .= $row["name"]." </option> \n";
	  		}
	  	}
	  	return $result;
	  }
	  
	  /** Relais bAjax vers des fonctions existantes **/
	  public static function bajax_search($parameters) {
	  	$filter = array();
	  	$filter["zip"] = PropRetriever::getProp($parameters,0);
	  	$filter["name"] = PropRetriever::getProp($parameters,1);
			if ($filter["zip"] != "" && strlen($filter["zip"]) < 3)
				return "<p class=\"error\"><center> Code Postal trop court ... (3 caractères minimum) </center> </p>";
			if ($filter["name"] != "" && strlen($filter["name"]) < 3)
				return "<p class=\"error\"><center> Nom de ville trop court ... (3 caractères minimum) </center> </p>";
			
	  	return self::showResult(self::lookFor($filter));
	  
	  }

	  
	  /** Recupération d'une liste de villes sur leurs code postaux **/
	  public static function bajax_getAsList($array) {
	  	$zip = PropRetriever::getProp($array,0);
	  	return self::getAsList($zip);
	  }
	  
	  private static function displayZip($z) {
	  	if ($z == self::$ForeignCity)
	  		return self::$ForeignDisplay;
	  	return $z;
	  }
	  
	}

?>